package com.cssw.fyzb.core.eao.acct;

import com.alibaba.fastjson.JSON;
import com.cssw.fyzb.core.es.EsClient;
import com.cssw.fyzb.core.model.eos.LiveRedPackSubEo;
import com.cssw.fyzb.core.util.DateUtil;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Jian Qin.
 */
@Component
public class LiveRedPackSubEaoImpl implements LiveRedPackSubEao{
    @Autowired
    private EsClient esClient;

    private final static String INDEX_NAME = "fyzb_red_pack_sub";
    private final static String TYPE_NAME = "red_pack_sub";

    @Override
    public String save(Long redPackId, Long liveId, Long fromUserId,
                       Long userId, BigDecimal money, BigDecimal takeMoney, Date date) {
        LiveRedPackSubEo liveRedPackSubEo = new LiveRedPackSubEo();
        liveRedPackSubEo.setRed_pack_id(redPackId);
        liveRedPackSubEo.setCreateTime(DateUtil.format(date));
        liveRedPackSubEo.setLive_id(liveId);
        liveRedPackSubEo.setMoney(money);
        liveRedPackSubEo.setTakeUserId(userId);
        liveRedPackSubEo.setUserId(fromUserId);
        liveRedPackSubEo.setTakeMoney(takeMoney);
        liveRedPackSubEo.setTradeId(getUniqueId());


        esClient.getClient()
                .prepareIndex(INDEX_NAME, TYPE_NAME)
                .setSource(JSON.parseObject(JSON.toJSONString(liveRedPackSubEo)))
                .get()
        ;
        return liveRedPackSubEo.getTradeId();
    }

    @Override
    public LiveRedPackSubEo queryOne(Long repackId, Long userId) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.filter().add(QueryBuilders.termQuery("takeUserId", userId));
        queryBuilder.filter().add(QueryBuilders.termQuery("red_pack_id", repackId));

        SearchResponse response = esClient.getClient()
                .prepareSearch(INDEX_NAME)
                .setTypes(TYPE_NAME)
                .setQuery(queryBuilder)
                .setSize(1)
                .get();

        if(response.getHits().totalHits > 0){
            SearchHit hit = response.getHits().getAt(0);
            return JSON.parseObject(JSON.toJSONString(hit.getSourceAsMap()), LiveRedPackSubEo.class);
        }

        return null;
    }

    private String getUniqueId() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); //精确到毫秒
        String timestamp = fmt.format(new Date()); // 时间戳，自动生成
        return timestamp + generateNonceStr(3);
    }

    private String generateNonceStr(int length) {
        length = length > 32 ? 32 : length;
        String chars = "0123456789";
        int maxPos = chars.length();
        String result = "";
        for (int i = 0; i < length; i++) {
            result += chars.charAt((int) Math.floor(Math.random() * maxPos));
        }
        return result;
    }
}
